package cn.lili.modules.member.serviceimpl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import cn.lili.common.exception.ServiceException;
import cn.lili.common.security.AuthUser;
import cn.lili.common.security.context.UserContext;
import cn.lili.common.utils.ResultUtil;
import cn.lili.common.utils.StringUtils;
import cn.lili.common.vo.ResultMessage;
import cn.lili.modules.member.entity.dos.CityDistribution;
import cn.lili.modules.member.entity.dos.CityDistributionCancel;
import cn.lili.modules.member.entity.dos.User;
import cn.lili.modules.member.entity.dto.CityDistributionDTO;
import cn.lili.modules.member.entity.dto.UserQueryDTO;
import cn.lili.modules.member.entity.enums.ComissStatusEnum;
import cn.lili.modules.member.mapper.CityDistributionMapper;
import cn.lili.modules.member.service.CityDistributionCancelService;
import cn.lili.modules.member.service.CityDistributionService;
import cn.lili.modules.member.service.UserService;
import cn.lili.modules.operationcenter.client.OperationCenterClient;
import cn.lili.modules.operationcenter.entity.dos.OperationCenter;
import cn.lili.modules.order.order.entity.vo.RegionalGroupingVO;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.Year;
import java.time.YearMonth;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author asus
 * @description 针对表【li_city_distribution(城主表)】的数据库操作Service实现
 * @createDate 2024-01-08 20:19:05
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class CityDistributionServiceImpl extends ServiceImpl<CityDistributionMapper, CityDistribution>
        implements CityDistributionService {
    private final UserService userService;
    private final OperationCenterClient operationCenterClient;
    private final CityDistributionCancelService cityDistributionCancelService;
    /**
     * 本月是不是城主
     *
     * @return true/false
     */
    @Override
    public ResultMessage<Object> isCastellan() {
        //所有区域
        CityDistribution query = new CityDistribution();
        query.setMemberId(UserContext.getCurrentId());
        CityDistribution castellan = this.getCastellan(query);
        return castellan != null ? ResultUtil.data(true) : ResultUtil.data(false);
    }

    /**
     * 区域城主
     *
     * @param cityDistribution 查询对象
     * @return 当前区域城主
     */
    @Override
    public CityDistribution getCastellan(CityDistribution cityDistribution) {
        LambdaQueryWrapper<CityDistribution> distributionLambdaQueryWrapper = this.createWrapper(cityDistribution);
        distributionLambdaQueryWrapper.last("limit 1");
        return super.getOne(distributionLambdaQueryWrapper);
    }

    /**
     * 构建条件
     *
     * @param cityDistribution 参数
     * @return 条件
     */
    public LambdaQueryWrapper<CityDistribution> createWrapper(CityDistribution cityDistribution) {
        LambdaQueryWrapper<CityDistribution> distributionLambdaQueryWrapper = new LambdaQueryWrapper<>();
        if (StringUtils.isNotEmpty(cityDistribution.getDistrictCode())) {
            distributionLambdaQueryWrapper.eq(CityDistribution::getDistrictCode, cityDistribution.getDistrictCode());
        }
        if (StringUtils.isNotEmpty(cityDistribution.getMemberId())) {
            distributionLambdaQueryWrapper.eq(CityDistribution::getMemberId, cityDistribution.getMemberId());
        }
        //本年月数据
        distributionLambdaQueryWrapper.eq(CityDistribution::getYearDate, Year.now().getValue());
        distributionLambdaQueryWrapper.eq(CityDistribution::getMonthDate, LocalDate.now().getMonthValue());
        distributionLambdaQueryWrapper.orderByDesc(CityDistribution::getCreateTime);
        return distributionLambdaQueryWrapper;
    }

    /**
     * 获取城主区域分组
     */
    @Override
    public ResultMessage<Object> getCastellanRegionGroup() {
        CityDistribution query = new CityDistribution();
        query.setMemberId(UserContext.getCurrentId());
        LambdaQueryWrapper<CityDistribution> queryWrapper = this.createWrapper(query);
        List<CityDistribution> cityDistributionList = super.list(queryWrapper);
        if (CollectionUtil.isEmpty(cityDistributionList)) {
            return ResultUtil.data(new ArrayList<>());
        }
        //将得到的区域，转换拼接
        List<RegionalGroupingVO> result = new ArrayList<>();
        for (CityDistribution cityDistribution : cityDistributionList) {
            RegionalGroupingVO groupingVO = new RegionalGroupingVO();
            groupingVO.setId(cityDistribution.getDistrictCode());
            groupingVO.setName(cityDistribution.getCityName() + "-" + cityDistribution.getDistrictName());
            result.add(groupingVO);
        }
        return ResultUtil.data(result.stream().distinct().collect(Collectors.toList()));
    }

    /**
     * 分页获取城主列表
     *
     * @param dto
     * @return
     */
    @Override
    public Page<CityDistribution>  getCityDistribution(CityDistributionDTO dto) {
        LambdaQueryWrapper<CityDistribution> query = new LambdaQueryWrapper<>();
        query.eq(StringUtils.isNotEmpty(dto.getId()), CityDistribution::getId, dto.getId());
        query.eq(StringUtils.isNotEmpty(dto.getPrivinceCode()), CityDistribution::getPrivinceCode, dto.getPrivinceCode());
        query.eq(StringUtils.isNotEmpty(dto.getCityCode()), CityDistribution::getCityCode, dto.getCityCode());
        query.eq(StringUtils.isNotEmpty(dto.getDistrictCode()), CityDistribution::getDistrictCode, dto.getDistrictCode());
        //收益发放状态
        query.eq(dto.getComissStatus() != null, CityDistribution::getComissStatus, dto.getComissStatus());
        //日期条件
        if (StringUtils.isNotEmpty(dto.getDateParam())) {
            String[] dateStrArray = dto.getDateParam().split("-");
            query.eq(CityDistribution::getYearDate, Integer.valueOf(dateStrArray[0]));
            query.eq(CityDistribution::getMonthDate, Integer.valueOf(dateStrArray[1]));
            dto.setYearDate(Integer.valueOf(dateStrArray[0]));
            dto.setMonthDate(Integer.valueOf(dateStrArray[1]));
            LocalDate paramLocalDate = LocalDate.of(Integer.valueOf(dateStrArray[0]), Integer.valueOf(dateStrArray[1]), 1);
            dto.setStartLocalDate(paramLocalDate.toString());
            dto.setEndLocalDate(paramLocalDate.plusMonths(1).toString());
        } else {
            //默认为当月
            LocalDate currentDate = LocalDate.now();
            query.eq(CityDistribution::getYearDate, currentDate.getYear());
            query.eq(CityDistribution::getMonthDate, currentDate.getMonthValue());
            dto.setStartLocalDate(currentDate.withDayOfMonth(1).toString());
            dto.setEndLocalDate(currentDate.withDayOfMonth(1).plusMonths(1).toString());
        }
        //排序
        query.orderByDesc(CityDistribution::getCreateTime).orderByDesc(CityDistribution::getId);
        Page<CityDistribution> cpage = new Page<>();
        log.info("dot === {}", dto);
        if (dto.getPageNumber() > 0 && dto.getPageSize() > 0) {
            //页面分页查询
//            cpage = baseMapper.selectPage(new Page(dto.getPageNumber(), dto.getPageSize()), query);
            cpage = baseMapper.selectCityDistributionPage(new Page(dto.getPageNumber(), dto.getPageSize()), dto);
        } else {
            List<CityDistribution> list = baseMapper.selectList(query);
            cpage.setRecords(CollUtil.isNotEmpty(list) ? list : null);
        }
        if (CollUtil.isNotEmpty(cpage.getRecords())) {
            cpage.getRecords().stream().forEach(e -> {
                if (e.getComissStatus() != null) {
                    e.setComissStatusName(ComissStatusEnum.getByCode(e.getComissStatus()));
                }
                if (e.getDistributionStatus() != null && !e.getDistributionStatus()) {
                    e.setMemberId("");
                    e.setNickName("");
                }
                Double totalComiss = baseMapper.selectTotalComiss(e.getPrivinceCode(), e.getCityCode(), e.getDistrictCode(), dto.getStartLocalDate(), dto.getEndLocalDate());
                log.info("totalComiss == {}", totalComiss);
                e.setTotalComiss(totalComiss);
            });
        }
        return cpage;
    }

    @Override
    public Page<CityDistribution> historyEarnings(Page<CityDistribution> objectPage) {
        return baseMapper.historyEarnings(objectPage, UserContext.getCurrentId(), YearMonth.now().getYear(), YearMonth.now().getMonthValue());
    }


    /**
     * 取消城主资格
     *
     * @param dto
     * @return
     */
    @Override
    public ResultMessage<Object> cancelcityDistribution(CityDistributionDTO dto) {
        CityDistribution city = baseMapper.selectById(dto.getId());
        if (city != null && city.getDistributionStatus() && StringUtils.isNotEmpty(city.getMemberId())) {
            //取消城主
            city.setDistributionStatus(Boolean.FALSE);
            LambdaUpdateWrapper<CityDistribution> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.eq(CityDistribution::getId, city.getId());
            updateWrapper.set(CityDistribution::getDistributionStatus, Boolean.FALSE);
            updateWrapper.set(CityDistribution::getRequired, Boolean.FALSE);
            updateWrapper.set(CityDistribution::getDistributionId, null);
            updateWrapper.set(CityDistribution::getNickName, null);
            updateWrapper.set(CityDistribution::getMemberId, null);
            //新增一条取消记录
            CityDistributionCancel cityDistributionCancel = new CityDistributionCancel();
            cityDistributionCancel.setDistributionId(city.getDistributionId());
            cityDistributionCancel.setDistrictCode(city.getDistrictCode());
            cityDistributionCancel.setDistrictName(city.getDistrictName());
            cityDistributionCancel.setMemberId(city.getMemberId());
            cityDistributionCancel.setYearDate(city.getYearDate());
            cityDistributionCancel.setMonthDate(city.getMonthDate());
            cityDistributionCancelService.save(cityDistributionCancel);

            return super.update(updateWrapper) ? ResultUtil.success() : ResultUtil.error(400, "取消失败");
        }
        return ResultUtil.error(400, "未查询到需要取消的城主信息");
    }

    /**
     * 指定城主
     *
     * @param dto
     * @return
     */
    @Override
    public ResultMessage<Object> setCityDistributionUser(CityDistributionDTO dto) {
        if (StringUtils.isEmpty(dto.getMemberId())) {
            return ResultUtil.error(400, "城主用户id不可为空");
        }
        CityDistribution city = baseMapper.selectById(dto.getId());
        this.checkSetCityDis(city);
        UserQueryDTO userQuery = new UserQueryDTO();
        userQuery.setUserId(dto.getMemberId());
        List<User> users = userService.selectUserForCityDistributionByAccount(userQuery);
        if (CollUtil.isEmpty(users)) {
            return ResultUtil.error(400, "该用户暂不满足成为城主的条件");
        }
        city.setMemberId(dto.getMemberId());
        city.setNickName(users.get(0).getNickName());
        city.setDistributionStatus(Boolean.TRUE);
        city.setRequired(Boolean.TRUE);

        //删除取消记录
        this.updateCityDistributionCancel(city.getDistrictCode());

        return baseMapper.updateById(city) > 0 ? ResultUtil.success() : ResultUtil.error(400, "指定失败");
    }

    /**
     * 判断是否可指定城主
     *
     * @param city
     */
    private void checkSetCityDis(CityDistribution city) {
        //判断是否是当月,并且城主
        LocalDate currentDate = LocalDate.now();
        if (currentDate.getYear() != city.getYearDate() || city.getMonthDate() != currentDate.getMonthValue()) {
            throw new ServiceException("仅支持指定当月城主");
        }
//        if (null != city && StringUtils.isEmpty(city.getMemberId()) && !city.getDistributionStatus()) {
//            throw new ServiceException("该条城主数据已存在城主");
//        }
    }

    /**
     * 更换城主
     *
     * @param dto
     * @return
     */
    @Override
    public ResultMessage<Object> changeCityDistributionUser(CityDistributionDTO dto) {
        if (StringUtils.isEmpty(dto.getMemberId())) {
            return ResultUtil.error(400, "城主用户id不可为空");
        }
        CityDistribution city = baseMapper.selectById(dto.getId());
        if (null != city) {
            if (city.getId().equals(dto.getMemberId())) {
                return ResultUtil.error(400, "当前用户已是该区域城主");
            }
            UserQueryDTO userQuery = new UserQueryDTO();
            userQuery.setUserId(dto.getMemberId());
            List<User> users = userService.selectUserForCityDistributionByAccount(userQuery);
            if (CollUtil.isEmpty(users)) {
                return ResultUtil.error(400, "该用户暂不满足成为城主的条件");
            }
            city.setMemberId(dto.getMemberId());
            city.setNickName(users.get(0).getNickName());
            city.setRequired(true);
            //删除取消记录
            this.updateCityDistributionCancel(city.getDistrictCode());

            return baseMapper.updateById(city) > 0 ? ResultUtil.success() : ResultUtil.error(400, "指定失败");
        }
        return ResultUtil.error(400, "操作失败");
    }

    /**
     * 删除取消记录
     * @param code 区域id
     */
    private void updateCityDistributionCancel(String code) {
        if (StringUtils.isEmpty(code)) {
            return;
        }
        LambdaUpdateWrapper<CityDistributionCancel> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(CityDistributionCancel::getDistrictCode, code);
        updateWrapper.eq(CityDistributionCancel::getYearDate, YearMonth.now().getYear());
        updateWrapper.eq(CityDistributionCancel::getMonthDate, YearMonth.now().getMonthValue());
        updateWrapper.set(CityDistributionCancel::getDeleteFlag, Boolean.TRUE);
        cityDistributionCancelService.update(updateWrapper);
    }

    /**
     * 根据区域，年月获取城主
     *
     * @param regionId 区域
     * @param year     年
     * @param month    月
     * @return 城主
     */
    @Override
    public CityDistribution getCastellanByCodeYearMonth(String regionId, Integer year, Integer month) {
        LambdaQueryWrapper<CityDistribution> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CityDistribution::getDistrictCode, regionId);
        queryWrapper.eq(CityDistribution::getYearDate, year);
        queryWrapper.eq(CityDistribution::getMonthDate, month);
        queryWrapper.orderByDesc(CityDistribution::getCreateTime);
        queryWrapper.last("limit 1");
        return super.getOne(queryWrapper);
    }

    /**
     * 运营中心-城主统计-城主列表
     *
     * @param dto
     * @return
     */
    @Override
    public Page<CityDistribution> operationCityDistributionList(CityDistributionDTO dto) {
        AuthUser authUser = UserContext.getCurrentUser();
        OperationCenter operation = operationCenterClient.getOperationCenter(authUser.getId());
        if (null == operation) {
            throw new ServiceException("登陆信息未找到运营中心账号");
        }
        dto.setPrivinceCode(operation.getProvinceId());
        Page<CityDistribution> page = this.getCityDistribution(dto);
        /*if (!page.getRecords().isEmpty()) {
            page.getRecords().forEach(cityDistribution -> {
                if (StringUtils.isNotEmpty(cityDistribution.getMemberId())) {
                    User user = userService.getById(cityDistribution.getMemberId());
                    if (null != user) {
                        cityDistribution.setNickName(user.getFyName());
                        cityDistribution.setMemberId(user.getAccount());
                    }
                }
            });
        }*/
        return page;
    }


}




